﻿<#include "/org/alfresco/components/form/controls/common/utils.inc.ftl" />

<#assign controlId = fieldHtmlId + "-cntrl">

<#if field.control.params.optionSeparator??>
   <#assign optionSeparator=field.control.params.optionSeparator>
<#else>
   <#assign optionSeparator=",">
</#if>
<#if field.control.params.labelSeparator??>
   <#assign labelSeparator=field.control.params.labelSeparator>
<#else>
   <#assign labelSeparator="|">
</#if>

<#assign fieldValue=field.value>

<#if fieldValue?string == "" && field.control.params.defaultValueContextProperty??>
   <#if context.properties[field.control.params.defaultValueContextProperty]??>
      <#assign fieldValue = context.properties[field.control.params.defaultValueContextProperty]>
   <#elseif args[field.control.params.defaultValueContextProperty]??>
      <#assign fieldValue = args[field.control.params.defaultValueContextProperty]>
   </#if>
</#if>

<div class="form-field">
   <#if form.mode == "view">
      <div class="viewmode-field">
         <#if field.mandatory && !(fieldValue?is_number) && fieldValue?string == "">
            <span class="incomplete-warning"><img src="${url.context}/res/components/form/images/warning-16.png" title="${msg("form.field.incomplete")}" /><span>
         </#if>
         <span class="viewmode-label">${field.label?html}:</span>
         <#if fieldValue?string == "">
            <#assign valueToShow=msg("form.control.novalue")>
         <#else>
            <#assign valueToShow=fieldValue>
            <#if field.control.params.options?? && field.control.params.options != "">
               <#list field.control.params.options?split(optionSeparator) as nameValue>
                  <#if nameValue?index_of(labelSeparator) == -1>
                     <#if nameValue == fieldValue?string || (fieldValue?is_number && fieldValue?c == nameValue)>
                        <#assign valueToShow=nameValue>
                        <#break>
                     </#if>
                  <#else>
                     <#assign choice=nameValue?split(labelSeparator)>
                     <#if choice[0] == fieldValue?string || (fieldValue?is_number && fieldValue?c == choice[0])>
                        <#assign valueToShow=msgValue(choice[1])>
                        <#break>
                     </#if>
                  </#if>
               </#list>
            </#if>
         </#if>
         <span class="viewmode-value">${valueToShow?html}</span>
      </div>
   <#else>
      <label for="${fieldHtmlId}">${field.label?html}:<#if field.mandatory><span class="mandatory-indicator">${msg("form.required.fields.marker")}</span></#if></label>
      <#if field.control.params.options?? && field.control.params.options != "">
         <select id="${fieldHtmlId}" name="-" tabindex="0" 
			   <#if field.control.params.onClick??>onchange="${field.control.params.onClick}"<#else>onchange="setInputValue(this.options[this.selectedIndex].value)</#if>
               <#if field.description??>title="${field.description}"</#if>
               <#if field.control.params.size??>size="${field.control.params.size}"</#if> 
               <#if field.control.params.styleClass??>class="${field.control.params.styleClass}"</#if>
               <#if field.control.params.style??>style="${field.control.params.style}"</#if>
               <#if field.disabled  && !(field.control.params.forceEditable?? && field.control.params.forceEditable == "true")>disabled="true"</#if>>
                    <option value="">Parinkite naudotoją sekančiam žingsniui...</option>
         </select>
         <@formLib.renderFieldHelp field=field />
      <#else>
         <select id="${fieldHtmlId}" name="-" tabindex="0"
			  <#if field.control.params.onClick??>onchange="${field.control.params.onClick}"<#else>onchange="setInputValue(this.options[this.selectedIndex].value)"</#if>
			  <#if field.description??>title="${field.description}"</#if>
              <#if field.control.params.size??>size="${field.control.params.size}"</#if> 
              <#if field.control.params.styleClass??>class="${field.control.params.styleClass}"</#if>
              <#if field.control.params.style??>style="${field.control.params.style}"</#if>
              <#if field.disabled  && !(field.control.params.forceEditable?? && field.control.params.forceEditable == "true")>disabled="true"</#if>>
                <option value="">Parinkite naudotoją sekančiam žingsniui...</option>
         </select>
      </#if>
   </#if>
    <input type="hidden" id="${controlId}-added" name="${field.name}_added" />
    <input type="hidden" id="${controlId}-removed" name="${field.name}_removed" />
	<script type="text/javascript">//<![CDATA[
	function getNodeRefs(refs) {
		var strin = "";
		var noderefs = refs;
		var n = noderefs.split("workspace://SpacesStore/");
		for (var i = 1; i < n.length; i++) {
			strin += n[i];
		}
		var m = strin.replace(/,/g, "|");
		return m;
	}
	
	var updateJobTitle = function(res) {
		var resultu = eval('(' + res.serverResponse.responseText + ')');
		if (resultu.userInfo.length > 0) {
			$("input[name*=VadPareigos]").val(resultu.userInfo[0].jobTitle);
		} else {
			$("input[name*=VadPareigos]").val("{Nenurodyta}");
		}
		var event1 = jQuery.Event("keydown");
		var event2 = jQuery.Event("keyup");
		event1.keyCode = 50;
		event2.keyCode = 50;
		$("input[name*=VadPareigos]").trigger(event1); 
		$("input[name*=VadPareigos]").trigger(event2); 	
	};

	function getJobTitle(personRef) {
		setInputValue(personRef);
		var nodeRef = getNodeRefs(personRef);
		Alfresco.util.Ajax.jsonGet({
			url : Alfresco.constants.PROXY_URI + "user/info/" + nodeRef + "/"+ (new Date().getTime()),
			successCallback : {
				fn : updateJobTitle,
				scope : this
			},
			failureCallback : {
				fn : function() {},
				scope : this
			}
		});
	}

	function setInputValue(nodeRef) {
		var inputId = "${controlId}-added";
		$('#' + inputId).val(nodeRef);
	}

	var updateFields = function(res) {
		var fieldId 	= "${fieldHtmlId}";
		var inputId = "${controlId}-added";
		var fieldHtmlId = '#'+fieldId;
		var oneOrMoreDefault = false;
		var firstValue = null, nodeVal = null;
	
		var result = eval('(' + res.serverResponse.responseText + ')');
		
		if (result.members.length > 0) {
			$(fieldHtmlId).empty();
			for (var i = 0; i < result.members.length; i++ ) {
				var fullName = null;
				if (i === 0) {
					firstValue = "workspace://SpacesStore/"+result.members[0].userId;
				}
				var fieldValue = "workspace://SpacesStore/"+result.members[i].userId;
				if (result.members[i].firstName != "" && result.members[i].lastName != "") {
					fullName = result.members[i].firstName + ' ' + result.members[i].lastName;
				} else {
					fullName = result.members[i].userName;
				}
				var option = "<option value=" + "'" + fieldValue + "'" + ">"+ fullName + "</option>"; 
				$(fieldHtmlId).append(option);
				if (result.members[i].isDefault === 'true') {
					oneOrMoreDefault = true;
					$("select#" + fieldId + " option:eq("+i+")").attr('selected', true);
					$('#' + inputId).val(fieldValue);
				}
			}
			if (oneOrMoreDefault === false) {
				$("select#" + fieldId + "option:eq("+0+")").attr('selected', true); 
				$('#' + inputId).val(firstValue); 
			}
		}
		nodeVal = $('#' + inputId).val();
		getJobTitle(nodeVal);
  };

    Alfresco.util.Ajax.jsonGet({
		url : Alfresco.constants.PROXY_URI + "select/users/"+ "${field.control.params.usersGroup}"+"/"+ (new Date().getTime()),
		successCallback : {
			fn : updateFields,
			scope : this
		},
		failureCallback : {
			fn : function() {},
			scope : this
		}
    });
   //]]>
   </script>
</div>
